<template>
	<view>
		<u-navbar :is-back="false" :border-bottom="false">
			<view class="u-flex u-row-between u-flex-1 u-p-x-30">
				<view>
					<text class="u-font-38 text-bold">通讯录</text>
				</view>
				<!-- <navigator url="/pages/search/search" hover-class="none">
					<u-icon name="search" size="34"></u-icon>
				</navigator> -->
				<view class="plus" :class="{show:plus.show}" @tap="plus.show=!plus.show">
					<view class="icon iconfont icon-increase u-font-50"></view>
					<view class="oper">
						<navigator url="/pages/friend/search" hover-class="none" class="u-p-y-20 u-p-x-30 u-flex">
							<text class="cuIcon-friendadd u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">添加好友</text>
						</navigator>
						<view class="u-p-y-20 u-p-x-30 u-flex" @tap="scan">
							<text class="cuIcon-scan u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">扫一扫</text>
						</view>
						<navigator url="/pages/group/create" hover-class="none" class="u-p-y-20 u-p-x-30 u-flex">
							<text class="cuIcon-group u-m-r-20 u-font-50 text-bold"></text>
							<text class="u-font-34 text-bold u-m-l-6">创建群聊</text>
						</navigator>
					</view>
				</view>
			</view>
		</u-navbar>
		<view class="search-place">
			
		</view>
		<navigator url="/pages/search/search" hover-class="none" class="search-box u-flex u-p-x-30" :style="{top:`${navBar}px`}">
			<!-- <u-search placeholder="搜索" :show-action="false" :disabled="true"></u-search> -->
			<view class="u-flex bg-gray round u-flex-1 u-p-x-20 u-p-y-12">
				<text class="iconfont icon-sousuo u-font-30 u-m-r-10 text-grey"></text>
				<text class="u-font-28 text-grey">搜索</text>
			</view>
		</navigator>
		<navigator url="/pages/group/list" class="u-flex u-p-x-30 u-p-y-20 u-border-bottom bg-white">
			<view class="cover text-white" style="background-color: #57bd6c;">
				<text class="iconfont icon-groupfill"></text>
			</view>
			<text class="u-m-l-20 u-font-34">群聊</text>
		</navigator>
		<!-- <navigator url="/pages/group/petition/list" class="u-flex u-p-x-30 u-p-y-20 u-border-bottom bg-white">
			<view class="cover text-white" style="background-color: #57bd6c;">
				<text class="iconfont icon-bellfill"></text>
			</view>
			<text class="u-m-l-20 u-font-34">群通知</text>
			<view class="u-flex-1">
			
			</view>
			<view class="u-flex u-row-center round bg-red" style="width: 40rpx; height: 40rpx;" v-if="groupJoinCount">
				{{groupJoinCount}}
			</view>
		</navigator> -->
		<navigator url="/pages/friend/petition" class="u-flex u-p-x-30 u-p-y-20 u-border-bottom bg-white">
			<view class="cover text-white" style="background-color: #eda252;">
				<text class="iconfont icon-add-friends"></text>
			</view>
			<text class="u-m-l-20 u-font-34">好友申请</text>
			<view class="u-flex-1">

			</view>
			<view class="u-flex u-row-center round bg-red" style="width: 40rpx; height: 40rpx;" v-if="apprCount">
				{{apprCount}}
			</view>
		</navigator>
	<!-- 	<view @tap="kefu" class="u-flex u-p-x-30 u-p-y-20 u-border-bottom bg-white">
			<u-avatar src="/static/logo.png" mode="square"></u-avatar>
			<text class="u-m-l-20 u-font-34">快聊客服</text>
		</view> -->
		<block v-for="(section,index) in users" :key="section.letter">
			<view class="point" :class="`anchor_${section.letter}`" :data-index="index"></view>
			<view class="anchor u-p-x-30 u-p-y-10" :style="{top:`${anchorTop}px`}">{{section.letter}}</view>
			<view class="section">
				<navigator :url="`/pages/user/info?id=${user.userId}`" hover-class="none" class="u-flex u-p-x-30 u-p-y-20 u-border-bottom bg-white"
					v-for="(user,index) in section.list" 
					:key="user.userId">
					<u-avatar :src="user.saveAvatar||user.avatarUrl" mode="square"></u-avatar>
					<text class="u-m-l-20 u-font-34" style="font-weight: 400;">{{user.remarks||user.userName}}</text>
				</navigator>
			</view>
		</block>
		<view class="indexer_sidebar"
			@touchstart.stop.prevent="onTouchStart"
			@touchmove.stop.prevent="onTouchMove"
			@touchend.stop.prevent="onTouchEnd"
			@touchcancel.stop.prevent="onTouchEnd"
		>
			<view class="item" :class="{cur:index==curPointIndex}" v-for="(section,index) in users" :key="section.letter">
				{{section.letter}}
			</view>
			<view class="alert" v-if="touching">
				{{users[moveIdx].letter}}
			</view>
		</view>
		<view v-show="false">
			{{unread}}
		</view>
		<real-dialog v-model="realAsk.show"></real-dialog>
		<!-- #ifdef APP-PLUS -->
		<updatepage ref="updatepage" />
		<!-- #endif -->
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	import updatepage from "@/components/updatepage.vue"
	// #endif
	import realDialog from "@/components/dialogs/realname/index.vue"
	import {
		jumpTo,
		delay,
		toast
	} from "@/utils/util.js"
	import {
		matching
	} from '@/utils/pinyin.js'
	import {
		mapGetters,
		mapActions
	} from "vuex"
	import {
		ConversationType
	} from "@/entity/ConversationType"
	import { scanCode } from "@/utils/file"
	export default {
		components:{
			realDialog,
			// #ifdef APP-PLUS
			updatepage
			// #endif
		},
		data() {
			return {
				scrollTop: 0,
				touching:false, 
				sidebarRect:null, 
				pointRects:[], 
				moveIdx:0,
				plus:{
					show:false
				},
				realAsk:{
					show:false,
				},
			}
		},
		computed:{
			...mapGetters('chat',['unread']),
			...mapGetters('addr',['friends','apprCount','groupJoinCount']),
			...mapGetters('user',['userId','isReal']),
			...mapGetters('system',['examine']),
			anchorTop(){
				return this.navBar+uni.upx2px(90)
			},
			users(){
				const res = this.friends.reduce((res,item)=>{
					const firstChar = item.remarks.slice(0,1)||item.userName.slice(0,1)
					let letter = ''
					if(/[a-zA-z]/.test(firstChar)){
						letter=firstChar
					}else{
						const py = matching(firstChar)
						letter = !!py?py.slice(0,1):'#'
					}
					letter = letter.toUpperCase()
					if(!res[letter]){
						res[letter] = []
					}
					res[letter].push(item)
					return res
				},{})
				return Object.entries(res).sort(([[next]],[[pre]])=>{
					if(pre=='#'){
						return -1
					}else if(next=='#'){
						return 1
					}else{
						return next.charCodeAt()-pre.charCodeAt()
					}
				}).map(([letter,list])=>({letter,list}))
			},
			curPointIndex(){
				let idx = -1;
				this.pointRects.some(({top},index)=>{
					if(this.scrollTop+this.navBar>=top){
						idx = index
					}else{
						return true
					}
				})
				return idx
			}
		},
		watch:{
			users(){
				this.initPointRects()
			}
		},
		onReady() {
			// #ifdef APP-PLUS
			const upRef = this.$refs.updatepage
			upRef.check().then(({needUp,lastVersion})=>{
				console.log(needUp,lastVersion)
				if(!needUp){
					return
				}
				upRef.upgrade();
				if(lastVersion.updateType==2){
					upRef.upgradeEvent()
				}
			})
			// #endif
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onShow() {
			this.fetchAssets()
		},
		async onPullDownRefresh() {
			try{
				await this.pullDownRefresh()
			}finally{
				uni.stopPullDownRefresh()
			}
		},
		onReachBottom() {
			this.reachBottom()
		},
		methods: {
			load(){
			},
			show(){

			},
			async pullDownRefresh() {
				this.fetchAssets()
				await this.fetchAllFriends()
			},
			async reachBottom(){

			},
			...mapActions('chat', ['setConversation']),
			...mapActions('addr',['fetchAllFriends']),
			...mapActions('wallet',['fetchAssets']),
			initPointRects(){
				uni.createSelectorQuery().in(this).selectAll('.point').boundingClientRect((rects)=>{
					this.pointRects = rects
				}).exec()
			},
			scrollToAnchor(index){
				const curAnchor = this.users[index]
				uni.createSelectorQuery().in(this).select(`.anchor_${curAnchor.letter}`).boundingClientRect(({top})=>{
					uni.pageScrollTo({
						duration:0,
						scrollTop:top+this.scrollTop+1-this.navBar
					})
				}).exec()
			},
			computeMoveIdx(top){
				if(!this.sidebarRect){
					return 0
				}
				const itemHeight = this.sidebarRect.height/this.users.length
				const index = Math.floor((top - this.sidebarRect.top) / itemHeight)
				if(index<0){
					return 0
				}else if(index>this.users.length-1){
					return this.users.length-1
				}
				return index
			},
			onTouchStart(e){
				uni.createSelectorQuery().in(this).select('.indexer_sidebar').boundingClientRect((rect)=>{
					this.sidebarRect = rect
					this.touching = true
					const touche = e.touches[0]
					this.moveIdx = this.computeMoveIdx(touche.clientY)
					this.scrollToAnchor(this.moveIdx)
				}).exec();
			},
			onTouchMove(e){
				const touche = e.touches[0]
				this.moveIdx = this.computeMoveIdx(touche.clientY)
				this.scrollToAnchor(this.moveIdx)
			},
			onTouchEnd(e){
				this.$nextTick(()=>{
					this.touching = false
					this.sidebarRect = null
				})
			},
			kefu(){
				this.singleChat({
					userId:'000000000',
					avatarUrl:'/static/logo.png',
					userName:'快聊客服',
				})
			},
			singleChat(item){
				this.setConversation({
					id: item.userId,
					type: ConversationType.Single,
					avatar: item.avatarUrl,
					name: item.userName
				})
				jumpTo(`/pages/room/single?id=${item.userId}`)
			},
			async scan(){
				const {result} = await scanCode({scanType:['qrCode']})
				if(/^API:/.test(result)){
					const [fun,pram] =result.slice(4).split('?')
					const pramObj = !!pram?pram.split('&').map(item=>item.split('=')).reduce((r,[k,v])=>{r[k]=v; return r},{}):undefined;
					this[fun]&&this[fun](pramObj)
				}
				if(/^PATH/.test(result)){ 
					const url = result.slice(5)
					uni.navigateTo({
						url
					})
				}
				if(/^login:qr:/.test(result)){
					const id = result.slice(9)
					uni.navigateTo({
						url:`/pages/login/scan?id=${id}`
					})
				}
			},
			realGuard(){
				if(!this.isReal){
					this.realAsk.show = true
					throw new Error('请完成实名认证')
				}
			},
			realJump(url){
				this.realGuard()
				jumpTo(url)
			}
		}
	}
</script>
<style lang="scss" scoped>
	.list-cell{
		display: flex;
		padding: 20rpx 30rpx;
	}
	.cover{
		width: 90rpx;
		height: 90rpx;
		border-radius: 10rpx;
		font-size: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.plus{
		position: relative;
		.icon{
			transition: all 0.3s ease-out;
		}
		&::before{
			content: '';
			display: block;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 3;
			pointer-events: none;
			transition: all 0.3s ease-out;
		}
		.oper{
			position: absolute;
			bottom: -18rpx;
			right: -8rpx;
			white-space: nowrap;
			padding: 30rpx 40rpx 30rpx 10rpx;
			background-color: #FFFFFF;
			z-index: 4;
			transform: translateY(90%);
			border-radius: 10rpx;
			opacity: 0;
			transition: all 0.3s ease-out;
			pointer-events: none;
			&::before{
				content: '';
				position: absolute;
				top: -18rpx;
				right: 20rpx;
				border-left: 10rpx solid transparent;
				border-right: 10rpx solid transparent;
				border-bottom: 20rpx solid #FFFFFF;
			}
			.icon-img{
				width: 1em;
				height: 1em;
			}
		}
		&.show{
			.icon{
				transform: rotate(45deg);
			}
			&::before{
				background-color: rgba($color: #000000, $alpha: 0.6);
				pointer-events: auto;
			}
			.oper{
				opacity: 1;
				transform: translateY(100%);
				pointer-events: auto;
			}
		}
		
	}
	.anchor{
		position: sticky;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: #F5F6F7;
	}
	.indexer_sidebar{
		position: fixed;
		top: 50%;
		right: 0;
		transform: translateY(-50%);
		z-index: 100;
		.item{
			font-size: 22rpx;
			padding: 8rpx 18rpx;
			text-align: center;
			font-weight: 500;
			&.cur{
				color: #007aff;
			}
		}
		.alert{
			position: absolute;
			top: 50%;
			left: -10rpx;
			width: 120rpx;
			height: 120rpx;
			border-radius: 24rpx;
			font-size: 50rpx;
			color: #fff;
			background-color: rgba(0, 0, 0, 0.65);
			transform: translate(-100%,-50%);
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
	.search-place{
		height: 90rpx;
	}
	.search-box{
		position: fixed;
		left: 0;
		right: 0;
		background-color: #ffffff;
		z-index: 100;
		height: 90rpx;
	}
</style>